<template>
    <div class="process-type-container">
        <!-- 标题和操作按钮 -->
        <div class="header-section">
            <h2 class="page-title">工序分类</h2>
            <div class="action-buttons">
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <el-button @click="handleExport" :disabled="selectedRows.length === 0">
                    导出 ({{ selectedRows.length }})
                </el-button>
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-section">
            <el-input v-model="searchForm.classificationName" placeholder="请搜索" style="width: 300px" clearable
                @keyup.enter="handleSearch">
                <template #suffix>
                    <el-icon class="el-input__icon" @click="handleSearch">
                        <Search />
                    </el-icon>
                </template>
            </el-input>
        </div>

        <!-- 数据表格 -->
        <div class="table-section">
            <!-- 选择提示 -->
            <div class="selection-info" v-if="selectedRows.length > 0">
                <el-icon><InfoFilled /></el-icon>
                <span>已选择 {{ selectedRows.length }} 条数据</span>
                <el-button type="text" @click="clearSelection">清除选择</el-button>
            </div>
            
            <el-table ref="tableRef" :data="tableData" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="classificationCode" label="工序分类编号" width="150" />
                <el-table-column prop="classificationName" label="工序分类名称" />
                <el-table-column prop="sortOrder" label="排序" width="100" />
                <el-table-column prop="isEnabled" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.isEnabled ? 'success' : 'info'">
                            {{ scope.row.isEnabled ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="备注" />
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
            <el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="工序分类编号" prop="classificationCode">
                    <el-input v-model="form.classificationCode" placeholder="请输入" :disabled="isEdit" />
                </el-form-item>
                <el-form-item label="工序分类名称" prop="classificationName">
                    <el-input v-model="form.classificationName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="排序" prop="sortOrder">
                    <el-input-number v-model="form.sortOrder" :min="1" placeholder="请输入" style="width: 100%" />
                </el-form-item>
                <el-form-item label="状态" prop="isEnabled">
                    <el-switch v-model="form.isEnabled" active-text="启用" inactive-text="禁用" />
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, InfoFilled } from '@element-plus/icons-vue'
import {
    ProcessClassificationShow,
    ProcessClassificationAdd,
    ProcessClassificationUpdate,
    ProcessClassificationDelete,
    ProcessClassificationExport
} from '@/Https/server'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const tableRef = ref()

// 搜索表单
const searchForm = reactive({
    classificationName: ''
})

// 分页数据
const pagination = reactive({
    pageIndex: 1,
    pageSize: 10,
    total: 0
})

// 表格数据
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 表单数据
const form = reactive({
    id: 0,
    classificationCode: '',
    classificationName: '',
    sortOrder: 1,
    isEnabled: true,
    description: '',
    CreateName :''
})

// 表单验证规则
const rules: FormRules = {
    classificationCode: [
        { required: true, message: '请输入工序分类编号', trigger: 'blur' },
        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
    ],
    classificationName: [
        { required: true, message: '请输入工序分类名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
    ],
    sortOrder: [
        { required: true, message: '请输入排序', trigger: 'blur' }
    ]
}

// 计算属性
const dialogTitle = computed(() => {
    return isEdit.value ? '编辑工序分类' : '新增工序分类'
})

// 方法
const loadData = async () => {
    loading.value = true
    try {
        const params = {
            ...searchForm,
            pageIndex: pagination.pageIndex,
            pageSize: pagination.pageSize
        }
        const response: any = await ProcessClassificationShow(params)
        if (response.code === 200) {
            tableData.value = response.data.pageData
            pagination.total = response.data.totalCount
        } else {
            ElMessage.error(response.message || '获取数据失败')
        }
    } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    pagination.pageIndex = 1
    loadData()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageIndex = 1
    loadData()
}

const handleCurrentChange = (page: number) => {
    pagination.pageIndex = page
    loadData()
}

const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
}

const clearSelection = () => {
    selectedRows.value = []
    // 清除表格的选择状态
    if (tableRef.value) {
        tableRef.value.clearSelection()
    }
}

const resetForm = () => {
    Object.assign(form, {
        id: 0,
        classificationCode: '',
        classificationName: '',
        sortOrder: 1,
        isEnabled: true,
        description: ''
    })
    formRef.value?.clearValidate()
}

const handleAdd = () => {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row: any) => {
    isEdit.value = true
    Object.assign(form, row)
    dialogVisible.value = true
}

const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除工序分类"${row.classificationName}"吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const response: any = await ProcessClassificationDelete({ Id: row.id })
        if (response.code === 200) {
            ElMessage.success('删除成功')
            loadData()
        } else {
            ElMessage.error(response.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        const api = isEdit.value ? ProcessClassificationUpdate : ProcessClassificationAdd
        const response: any = await api(form)

        if (response.code === 200) {
            ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
            dialogVisible.value = false
            loadData()
        } else {
            ElMessage.error(response.message || (isEdit.value ? '修改失败' : '新增失败'))
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
    } finally {
        submitLoading.value = false
    }
}

const handleExport = async () => {
    try {
        // 检查是否有选中的行
        if (selectedRows.value.length === 0) {
            ElMessage.warning('请先选择要导出的数据')
            return
        }

        // 显示加载提示
        ElMessage.info('正在导出数据...')
        
        // 准备导出数据
        const exportData = {
            selectedIds: selectedRows.value.map(row => row.id),
            exportAll: false,
            classificationName: searchForm.classificationName || ''
        }

        // 调用导出接口
        const response: any = await ProcessClassificationExport(exportData)
        
        // 创建下载链接
        const blob = new Blob([response], { 
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `工序分类_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败，请重试')
    }
}

// 生命周期
onMounted(() => {
    loadData()
})
</script>

<style scoped>
.process-type-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
    margin: 0;
    color: #333;
    font-size: 24px;
    font-weight: 600;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.search-section {
    margin-bottom: 20px;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.selection-info {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    background-color: #f0f9ff;
    border-bottom: 1px solid #e8e8e8;
    color: #1890ff;
    font-size: 14px;
}

.selection-info .el-icon {
    color: #1890ff;
}

.pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-table) {
    border-radius: 8px;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #333;
    font-weight: 600;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-input-number) {
    width: 100%;
}
</style>
